package com.binarytree.simple;

public class Node {
    private int data;
    private Node left;
    private Node right;

    public Node(int data) {
        this.data = data;
    }

    public void setLeft(Node left) {
        this.left = left;
    }

    public void setRight(Node right) {
        this.right = right;
    }

    // 前序遍历
    public void preOrder() {
        // 输出当前节点
        System.out.printf("%d ", data);
        // 输出左节点
        if (left != null) {
            this.left.preOrder();
        }
        // 输出右节点
        if (right != null) {
            this.right.preOrder();
        }
    }

    // 中序遍历
    public void infixOrder() {
        // 输出左节点
        if (left != null) {
            this.left.infixOrder();
        }
        // 输出当前节点
        System.out.printf("%d ", data);
        // 输出右节点
        if (right != null) {
            this.right.infixOrder();
        }
    }

    // 后序遍历
    public void postOrder() {
        // 输出左节点
        if (left != null) {
            this.left.postOrder();
        }
        // 输出右节点
        if (right != null) {
            this.right.postOrder();
        }
        // 输出当前节点
        System.out.printf("%d ", data);
    }

    // 前序查找
    public Node preOrderSearch(int data) {
        if (this.data == data) {
            return this;
        }

        Node resNode = null;
        if (left != null) {
            resNode = left.preOrderSearch(data);
        }
        if (resNode != null) {
            return resNode;
        }

        if (right != null) {
            resNode = right.preOrderSearch(data);
        }
        return resNode;
    }

    // 中序查找
    public Node infixOrderSearch(int data) {

        Node resNode = null;
        if (left != null) {
            resNode = left.infixOrderSearch(data);
        }
        if (resNode != null) {
            return resNode;
        }

        if (this.data == data) {
            return this;
        }

        if (right != null) {
            resNode = right.infixOrderSearch(data);
        }
        return resNode;
    }

    // 后序查找
    public Node postOrderSearch(int data) {

        Node resNode = null;
        if (left != null) {
            resNode = left.postOrderSearch(data);
        }
        if (resNode != null) {
            return resNode;
        }

        if (right != null) {
            resNode = right.postOrderSearch(data);
        }
        if (resNode != null) {
            return resNode;
        }

        if (this.data == data) {
            return this;
        }
        return null;
    }
}
